package com.vanke.kotlin_mvp.taskdetail

import com.vanke.kotlin_mvp.data.Task
import com.vanke.kotlin_mvp.data.TaskDataSource
import com.vanke.kotlin_mvp.data.TaskRepository

/**
 * @name Kotlin_MVP
 * @package name：com.vanke.kotlin_mvp.taskdetail
 * @class describe
 * @anthor shiyuchuan
 * @time 2017/8/22 15:13
 */
class TaskDetailPresenter(private val taskId: String,
                          private val tasksRepository: TaskRepository,
                          private val taskdetaiView: TaskDetailContract.View)
    : TaskDetailContract.Presenter {

    init {
        taskdetaiView.presenter = this
    }

    override fun start() {
        openTask()
    }

    private fun openTask() {
        if (taskId.isEmpty()) {
            taskdetaiView.showMissingTask()
            return
        }
        taskdetaiView.setLoadingIndicator(true)
        tasksRepository.getTask(taskId, object : TaskDataSource.GetTaskCallback {
            override fun onTaskLoaded(task: Task) {
                with(taskdetaiView) {
                    if (!isActive) {
                        return
                    }
                    setLoadingIndicator(false)
                }
                showTask(task)
            }

            override fun onDataAvailable() {
                with(taskdetaiView) {
                    if (!isActive) {
                        return
                    }
                    showMissingTask()
                }
            }

        })
    }

    private fun showTask(task: Task) {
        with(taskdetaiView) {
            if (taskId.isEmpty()) {
                hideTitle()
                hideDescription()
            } else {
                showTitle(task.title)
                showDescription(task.description)
            }

            showCompletionStatus(task.isCompleted)
        }
    }

    override fun editTask() {
        if (taskId.isEmpty()) {
            taskdetaiView.showMissingTask()
            return
        }
        taskdetaiView.showEditTask(taskId)
    }

    override fun deleteTask() {
        if (taskId.isEmpty()) {
            taskdetaiView.showMissingTask()
            return
        }
        tasksRepository.deleteTask(taskId)
        taskdetaiView.showTaskDeleted()
    }

    override fun completeTask() {
        if (taskId.isEmpty()) {
            taskdetaiView.showMissingTask()
            return
        }
        tasksRepository.completeTask(taskId)
        taskdetaiView.showTaskMarkedCompleted()
    }

    override fun activateTask() {
        if (taskId.isEmpty()) {
            taskdetaiView.showMissingTask()
            return
        }
        tasksRepository.activateTask(taskId)
        taskdetaiView.showTaskMarkedActive()
    }

}